#ifndef SYSTEMTRAYMANAGER_H
#define SYSTEMTRAYMANAGER_H

#include <QObject>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
#include <QTimer>
#include "updatemanager.h"
#include "updatedialog.h"

class SystemTrayManager : public QObject
{
    Q_OBJECT

public:
    explicit SystemTrayManager(QObject* parent = nullptr);
    ~SystemTrayManager();

    // 初始化系统托盘
    void initialize();

    // 检查系统托盘是否可用
    bool isSystemTrayAvailable() const;

    // 显示系统托盘
    void show();

    // 隐藏系统托盘
    void hide();

    // 设置主窗口引用
    void setMainWindow(QWidget* mainWindow);

public slots:
    // 开始下载更新
    void onUpdateDownloadStarted();

    // 下载进度更新
    void onDownloadProgress(int progress, qint64 received, qint64 total);

    // 下载完成
    void onDownloadFinished(const QString& filePath);

    // 下载错误
    void onDownloadError(const QString& error);

    // 更新可用
    void onUpdateAvailable(const VersionManager::UpdateInfo& info);

    // 显示更新对话框
    void showUpdateDialog();

private slots:
    // 系统托盘图标点击
    void onTrayIconActivated(QSystemTrayIcon::ActivationReason reason);

    // 显示主窗口
    void showMainWindow();

    // 退出应用程序
    void quitApplication();

    // 检查更新
    void checkForUpdates();

    // 暂停/恢复下载
    void toggleDownload();

private:
    void setupTrayIcon();
    void setupContextMenu();
    void updateTrayIcon(bool downloading = false);
    void updateTrayTooltip(const QString& tooltip);
    void showNotification(const QString& title, const QString& message);
    QString formatProgress(int progress, qint64 received, qint64 total) const;
    QString formatFileSize(qint64 bytes) const;

private:
    QSystemTrayIcon* m_trayIcon;
    QMenu* m_contextMenu;
    QAction* m_showAction;
    QAction* m_updateAction;
    QAction* m_downloadAction;
    QAction* m_separator1;
    QAction* m_separator2;
    QAction* m_quitAction;

    QWidget* m_mainWindow;
    UpdateManager* m_updateManager;
    VersionManager::UpdateInfo m_currentUpdateInfo;

    // 下载状态
    bool m_isDownloading;
    int m_downloadProgress;
    qint64 m_downloadedBytes;
    qint64 m_totalBytes;

    // 定时器
    QTimer* m_progressTimer;

    // 图标
    QIcon m_appIcon;
    QIcon m_downloadIcon;

    // 标志
    bool m_initialized;
    bool m_updateAvailable;
};

#endif // SYSTEMTRAYMANAGER_H